from rest_framework import serializers
from . import models
from rest_framework.exceptions import ValidationError

class ClassMateDetailModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ClassMateDetail
        fields = ['address','class_mate_f']

    def validate_class_mate_f(self, attr):
        obj = models.ClassMateDetail.objects.filter(class_mate_f=attr)
        if obj:
            raise ValidationError("class_mate_f已经有记录了，一对一，只能有一条记录")
        return attr
class ClassMateForTeacherModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ClassMateModel
        fields = ['id','name']

class ClassMateForStudentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ClassMateModel
        fields = ['id','name']

class TeacherModelSerializer(serializers.ModelSerializer):
    # class_mate_f = ClassMateForTeacherModelSerializer(many=True,read_only=True)
    class Meta:
        model = models.TeacherModel
        fields = ['id','name','age','phone','class_mate_f']
        depth =2

    def validate_phone(self, attr):
        obj = models.TeacherModel.objects.filter(phone=attr)
        if obj:
            raise ValidationError('当前手机号码已经存在')
        return attr


class StudentModelSerializer(serializers.ModelSerializer):
    # class_mate_f = ClassMateForStudentModelSerializer(read_only=True)\

    class Meta:
        model = models.StudentModel
        fields = ['id','name','class_mate_f','age']
        depth = 2



class TeacherForClassMateMdoelserializer(serializers.ModelSerializer):
    class Meta:
        model = models.TeacherModel
        fields = ['id','name','phone']

class ClassDetailForClassMateModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.ClassMateDetail
        fields =['address']

class StudentForClassMate(serializers.ModelSerializer):
    class Meta:
        model = models.StudentModel
        fields = ['name','age']

class ClassMateModelSerializer(serializers.ModelSerializer):
    teachers = TeacherForClassMateMdoelserializer(many=True)
    detail = ClassDetailForClassMateModelSerializer(many=True)
    students = StudentForClassMate(many=True)
    class Meta:
        model = models.ClassMateModel
        fields =['id','name','teachers','students','detail']
        extra_kwargs = {
            'id':{'read_only':True},
            'teachers':{'read_only':True},
            'detail':{'read_only':True},
            'students':{'read_only':True},
        }
    def validate_name(self, attr):
        obj = models.ClassMateModel.objects.filter(name=attr)
        if obj:
            raise ValidationError('该班级名称已经存在了')
        return attr
